// utils/auth.ts
import jwt, { Secret, SignOptions } from 'jsonwebtoken'
import bcrypt from 'bcryptjs'

/**
 * 限制 JWT_EXPIRES_IN 只能是合法的时间字符串格式：
 * 例如 "7d", "12h", "30m", "45s" 等
 */
type ExpireTime = `${number}${'s' | 'm' | 'h' | 'd'}`

// 安全读取环境变量（并提供默认值）
const JWT_SECRET: Secret = process.env.JWT_SECRET || 'default-secret-key'
const JWT_EXPIRES_IN: ExpireTime =
  (process.env.JWT_EXPIRES_IN as ExpireTime) || '7d'

export interface TokenPayload {
  userId: string
  username: string
  role: string
}

/**
 * 生成 JWT Token
 */
export function generateToken(payload: TokenPayload): string {
  const options: SignOptions = {
    expiresIn: JWT_EXPIRES_IN, // 已通过 ExpireTime 类型限制
  }
  return jwt.sign(payload, JWT_SECRET, options)
}

/**
 * 验证 JWT Token
 */
export function verifyToken(token: string): TokenPayload | null {
  try {
    return jwt.verify(token, JWT_SECRET) as TokenPayload
  } catch (error) {
    return null
  }
}

/**
 * 加密密码
 */
export async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, 10)
}

/**
 * 验证密码
 */
export async function comparePassword(
  password: string,
  hash: string,
): Promise<boolean> {
  return bcrypt.compare(password, hash)
}
